#include "napi/native_api.h"
#include <hilog/log.h>
#include <sound/hdsp.h>
#include <thread>
napi_value jsCb;
napi_threadsafe_function tsfn;

struct ThreadSafeInfo {
    int sum;
};

struct ThreadSafeInfo threadInfo = { 1 };

static void CallJs(napi_env env, napi_value jsCb, void *context, void *data) {
    napi_value undefined, argv, ret;
    std::thread::id this_id = std::this_thread::get_id();
    OH_LOG_INFO(LOG_APP, "thread callJs %{public}d\n", this_id);
    struct ThreadSafeInfo *arg = (struct ThreadSafeInfo *)data;
    napi_create_int32(env, arg->sum, &argv);
    napi_call_function(env, undefined, jsCb, 1, &argv, &ret);
}

static napi_value ThreadSafeTest(napi_env env, napi_callback_info info)
{
    std::thread::id this_id = std::this_thread::get_id();
    OH_LOG_INFO(LOG_APP, "thread ThreadSafeTest %{public}d\n", this_id);
    size_t argc = 1;
    napi_value workName;
    napi_create_string_utf8(env, "threadSafeTest", NAPI_AUTO_LENGTH, &workName);
    napi_get_cb_info(env, info, &argc, &jsCb, nullptr, nullptr);
    napi_create_threadsafe_function(env, jsCb, nullptr, workName, 0, 1, nullptr, nullptr, nullptr, CallJs, &tsfn);
    std::thread otherTask([]() {
        std::thread::id this_id = std::this_thread::get_id();
        OH_LOG_INFO(LOG_APP, "thread otherTask %{public}d\n", this_id);
        struct ThreadSafeInfo *data = &threadInfo;
        for(int n = 0; n < 1000; n++) {
                data->sum += 1;
        }
        napi_acquire_threadsafe_function(tsfn);
        napi_call_threadsafe_function(tsfn, data, napi_tsfn_blocking);
    });
    otherTask.detach();
    return nullptr;
}

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
    napi_property_descriptor desc[] = {
        { "ThreadSafeTest", nullptr, ThreadSafeTest, nullptr, nullptr, nullptr, napi_default, nullptr }
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version =1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "entry",
    .nm_priv = ((void*)0),
    .reserved = { 0 },
};

extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
{
    napi_module_register(&demoModule);
}